package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.util.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName:Filter
 * Package:com.itheima.filter
 * Description:
 *
 * @Author 老大
 * @Create 2024/5/8 10:58
 * @Version 1.0
 */
@WebFilter(urlPatterns = {"/*"})
public class DemoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求链接
        String requestUrl = request.getRequestURL().toString();
        //如果资源链接是login选择放行
        if (requestUrl.contains("login")) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取token值
        String token = request.getHeader("token");
        //如果没有token返回到登陆页面
        if (token == null || token.equals("")) {
            Result result = Result.error("NOT_LOGIN");

            String jsonString = JSONObject.toJSONString(result);
            response.getWriter().write(jsonString);
            return;
        }

        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result result = Result.error("NOT_LOGIN");

            String jsonString = JSONObject.toJSONString(result);
            response.getWriter().write(jsonString);
            return;
        }

        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
